package com.example.Servlet;

import com.example.Service.NewsService;
import com.example.pojo.News;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "RankingServlet", value = "/RankingServlet")
public class RankingServlet extends HttpServlet {
    private NewsService newsService=new NewsService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();

        try {//从服务器获取播放量排序的新闻列表
            List<News> rankingList = newsService.getNewsByViewCountDesc(); // 自定义方法，查询轮播图数据

            // 2. 处理数据格式，适配前端需求
            List<Map<String, Object>> rankingData = new ArrayList<>();
            for (News news : rankingList) {
                Map<String, Object> item = new HashMap<>();
                item.put("newsId", news.getNewsId()); // 新闻ID，用于跳转详情页
                item.put("newsTitle",news.getNewsTitle());
                item.put("newsType",news.getNewsType());
                item.put("viewCount",news.getNewsViews());
                item.put("newsImg",news.getNewsImg());
//
                // 如果需要完整的图片Url,
                String imgUrl = "";
                if (news.getNewsImg() != null && !news.getNewsImg().trim().isEmpty()) {
                    String baseUrl = "http://localhost:8080/mydemo_war_exploded/images/";
                    imgUrl = baseUrl + news.getNewsImg(); // 如：http://xxx/images/xxx.png
                }
                item.put("imgUrl", imgUrl);

                rankingData.add(item);
            }

            // 3. 响应数据给前端
            map.put("code", 200);
            map.put("msg", "排行榜数据查询成功");
            map.put("data", rankingData);
        } catch (Exception e) {
            map.put("code", 500);
            map.put("msg", "排行榜数据查询失败：" + e.getMessage());
            e.printStackTrace();
        }

        response.getWriter().append(gson.toJson(map));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}